#include <iostream>
#include <assert.h>
#include <qstring.h>
#include <tws_debugging.h>
//#include <xqtinilayout.h>
#include <xinifile.h>

#include "xinfomatvolumetypeparser.h"

//#define _DEBUGING_VOLUME_

const char INI_SECTION[] = "";
const char INI_KEY_VOLUME[] = "volume";
const char VOLUME_INI_FILE[] = "/usr/infomat/boot.conf";

XInfomatVolumeTypeParser::XInfomatVolumeTypeParser() :
    m_result(INFOMAT_RESULT_OK)
{
}

XInfomatVolumeTypeParser::~XInfomatVolumeTypeParser()
{
}

void XInfomatVolumeTypeParser::getResource(QByteArray in_datagram)
{
    char* data = new char[in_datagram.size()];
    memcpy(data, in_datagram.data(), in_datagram.size());
    assert(INFOMAT_CONFIG_PROTOCOL == *data);

	STInfomatVolumeType * tmpdata = reinterpret_cast<STInfomatVolumeType*> (data);
	memcpy(&m_volumeType, tmpdata, sizeof(m_volumeType));

	tmpdata = NULL;
	if (NULL!=data)
	{
		delete data;
		data = NULL;
	}

#ifdef _DEBUGING_VOLUME_
    DEBUG("Volume checking ...");
    DEBUG("Pass in Data, After Conversion");
    DEBUG("protocol : %02x", m_volumeType.head.protocol);
    DEBUG("type     : %02d", m_volumeType.head.type);
    DEBUG("size     : %x", m_volumeType.head.size);
    DEBUG("result   : %02d", m_volumeType.head.result);
    DEBUG("command  : %02d", m_volumeType.head.command);
    DEBUG("volume   : %02d", m_volumeType.volume);
#endif

    switch (m_volumeType.head.command)
    {
        case INFOMAT_COMMAND_READ:
            read();
            break;

        case INFOMAT_COMMAND_WRITE:
            write();
            break;

        default:
            DEBUG("XVolumeParser: no such command");
            m_result = INFOMAT_RESULT_ERR;
            break;
    }

    return;
}

void XInfomatVolumeTypeParser::read()
{
    XIniFile iniFile;

    assert(0 == iniFile.open(VOLUME_INI_FILE));

    int keyValue;
    if (0 != iniFile.readInt(INI_SECTION, INI_KEY_VOLUME, keyValue))
    {
        DEBUG("Read KEY_VOLUME [FAIL]");
        m_result = INFOMAT_RESULT_ERR;
    }

    DEBUG("keyvalue: %d", keyValue);
    iniFile.close();
    m_volumeType.volume = keyValue;

    return;
}

void XInfomatVolumeTypeParser::write()
{
    XIniFile iniFile;
    assert(0 == iniFile.open(VOLUME_INI_FILE, EIniReadWrite));

    if (0 != iniFile.writeInt(INI_SECTION, INI_KEY_VOLUME, int(m_volumeType.volume)))
    {
        DEBUG("Write KEY_VOLUME [FAIL]");
        m_result = INFOMAT_RESULT_ERR;
    }

    iniFile.flush();
    return;
}

QByteArray XInfomatVolumeTypeParser::getOutDatagram()
{
    m_volumeType.head.result = m_result;
    QByteArray outdata = QByteArray (reinterpret_cast<char*> (&m_volumeType), sizeof(STInfomatVolumeType));
	return outdata;
}

